import re

import jwt
from django.conf import settings
from django.http import JsonResponse

from User.models import User


def verify_token(request):
    token = request.META["HTTP_TOKEN"]
    if "b'" in token:
        token=re.findall("\'(.*?)\'",token)[0]
    if token is None or token == "":
        return False
    else:
        res = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        u = User.objects.get(email=res["email"])
        if u.token != token:
            return False
        else:
            return res

def back_success(data):
    return JsonResponse({
        "message": "请求成功",
        "code": 200,
        "data": data,
    })

def back_failed(data):
    code=100
    if data=="登录状态失效，请重新登录":
        code=101
    if data == "参数错误":
        code = 102
    if str(data).__contains__("API异常"):
        code=103
    if data=="默认文件不可删除":
        code=104
    if data=="账号已存在":
        code=105
    if data=="账号已存在":
        code=106
    if data=="账号不存在":
        code=107
    return JsonResponse({
        "message": str(data),
        "code": 100,
        "data": "请查看message",
    })
